package com.matu.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.matu.domain.Adresse;



/**
 * Classe permettant de gérer l'api google.
 * @author matu
 *
 */
public class ServiceGoogle {
	private static String _uri = "https://maps.googleapis.com/maps/api/geocode/";
	private static String _key = "&key=AIzaSyDF78Xb1LgV2AXtFAvLZ4g1OuWmA5sUpls";
	private URL url;
	private HttpURLConnection connection = null;


	
	/**
	 * Permet d'obtenir sous forme JSON le résultat d'une requête.
	 * @param request
	 * @return JSON
	 * @throws IOException
	 */
	public String getJSONOfRequest(String request) throws IOException {

		String res = "";
		// On obtient le stream json
		String requestUri = _uri + "json?" + request + _key;

		url = new URL(requestUri);
		connection = (HttpURLConnection) url.openConnection();
		InputStream is = null;
		is = connection.getInputStream();

		if (is != null) {

			// On transforme le stream en string

			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					"utf8"));
			String line;

			while ((line = rd.readLine()) != null) {
				res += line;
			}
			rd.close();
		}

		return res;
	}

	/**
	 * Permet d'appeler le service google qui retourne les coordonées
	 * géographiques en fonction d'une adresse.
	 * 
	 * @param adresse
	 * @return
	 * @throws IOException 
	 * @throws ParseException 
	 */
	public ArrayList<Adresse> getServiceCoordFromAdresse(String adresse) throws IOException, ParseException {
		
		ArrayList<Adresse> coords = new ArrayList<Adresse>();
		adresse += " Toulouse 31500";
		adresse = adresse.replaceAll("\\s+", "%");

		String jsonString = getJSONOfRequest("address=" + adresse + "&sensor=true");
		
		if (jsonString != ""){

			// on parse
			JSONParser parser = new JSONParser();
			Object obj = parser.parse(jsonString);
			JSONObject jsonObject = (JSONObject) obj;

			JSONArray results = (JSONArray) jsonObject.get("results");


			if (results != null) {
				

				@SuppressWarnings("unchecked")
				Iterator<JSONObject> iteratorResults = results.iterator();
				while (iteratorResults.hasNext()) {
						
					JSONObject currentResult= iteratorResults.next();
					String formatted_address = (String) currentResult.get("formatted_address");
					
					JSONObject geometry = (JSONObject) currentResult.get("geometry");

					if (geometry != null) {
		
						
						JSONObject location = (JSONObject) geometry.get("location");
						
						if (location != null){
	
							Double lat = (Double) location.get("lat");
							Double lng = (Double) location.get("lng");
							
							Adresse newCord = new Adresse(formatted_address,lat,lng);
							coords.add(newCord);
						}
						

					}

				}
			}

		}

		return coords;
	}
}
